package com.bigstar.lolen_e;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

public class Utils {
	public static final String DATA_PATH = "/sdcard/Android/data/LOLDATA/";
	public static final String RINGTONE_PATH = "/sdcard/media/audio/ringtones/";
	public static Bitmap skin;
	public static boolean isNetwork(Context context){
		ConnectivityManager cmgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo wifiInfo = cmgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	    NetworkInfo mobileNetworkInfo = cmgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
	    NetworkInfo lteInfo = cmgr.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
		NetworkInfo activeNetwork = cmgr.getActiveNetworkInfo();
	    boolean wifi = false;
	    boolean mobileNetwork = false;
	    boolean lte = false;
	    if(mobileNetworkInfo != null){
	    	if(mobileNetworkInfo.isAvailable() && mobileNetworkInfo.isConnected()){
	    		mobileNetwork = true;
	    	}
	    }
	    if(activeNetwork != null){
	    	if(activeNetwork.isAvailable() && activeNetwork.isConnected()){
	    		mobileNetwork = true;
	    	}
	    }
	    if(wifiInfo != null){
	    	if(wifiInfo.isAvailable() && wifiInfo.isConnected()){
	    		wifi = true;
	    	}
	    }
	    if(lteInfo != null){
	    	if(lteInfo.isAvailable() && lteInfo.isConnected()){
	    		lte = true;
	    	}
	    }
	    if(wifi || mobileNetwork || lte){ 
	    	return true;
	    }
	    return false;
	}
	
	public static void setRingtone(Context context, int champid, String settingType) {
		String filepath = "/sdcard/media/audio/ringtones/testmusic4.mp3";
		File file = new File(filepath);
		if (!file.exists()) {
			file.mkdirs();
		}
		try {
			ContentValues values = new ContentValues();
			values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
			values.put(MediaStore.MediaColumns.TITLE, ChampionData.champions.get(champid).name_en);
			values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
			values.put(settingType, true);
			Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
			context.getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + file.getAbsolutePath() + "\"", null);
			Uri newUri = context.getContentResolver().insert(uri, values);
			RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(context, "벨소리 설정에 실패했습니다.", Toast.LENGTH_SHORT).show();
			return;
		}
		Toast.makeText(context, "벨소리 설정이 완료되었습니다.", Toast.LENGTH_SHORT).show();
	}
	
	public static Bitmap loadBitmap(Context context, String path, String fileName) {
		Bitmap bm = null;
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			bm = BitmapFactory.decodeFile(DATA_PATH + path + "/" + fileName);
		}
		return bm;
	}
	
	public static Bitmap loadBitmap(Context context, String urlStr) {
		Bitmap bitmap = null;
		AssetManager mngr = context.getResources().getAssets();
		InputStream is = null;
		try{
			is = mngr.open(urlStr, AssetManager.ACCESS_BUFFER);
			bitmap = BitmapFactory.decodeStream(is);
		}catch(Exception e){
			
		} 
		return bitmap;
	}

	public static Bitmap getBitmapFromUrl(String imageURL) {
		Bitmap imgBitmap = null;
		HttpURLConnection conn = null;
		BufferedInputStream bis = null;
		try {
			URL url = new URL(imageURL);
			conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			int nSize = conn.getContentLength();
			bis = new BufferedInputStream(conn.getInputStream(), nSize);
			imgBitmap = BitmapFactory.decodeStream(bis);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return imgBitmap;
	}
	
	
	public static String getXMLFileFromAssets(Context context, String path) throws IOException {
		AssetManager assetManager = context.getResources().getAssets();
		AssetInputStream ais = (AssetInputStream)assetManager.open(path);      
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        String line;
        StringBuilder data = new StringBuilder();
        while((line=br.readLine()) != null)
        	data.append(line);
        return data.toString();
	}
	
	
	
	public static void saveBitmap(Context context,Bitmap bm, String path, String fileName, Boolean option) {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED) && option) {
			String dirPath = DATA_PATH + path;
			File dir = new File(dirPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(DATA_PATH + path + "/" + fileName);
			if (file.exists()) {
				return;
			}
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(file);
				bm.compress(CompressFormat.JPEG, 80, fos);
			} catch (FileNotFoundException e) {
				Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
			} catch (SecurityException e) {
				Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
			} finally {
				if (fos != null){
					try {
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public static void showDialog(Context context, String title, String message){
		AlertDialog.Builder alert = new AlertDialog.Builder(context);
		alert.setTitle(title)
		.setMessage(message);
		alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		alert.setIcon(R.drawable.icon);
		alert.create().show();	
	}
	

	public static boolean loadObject(Context context, String pathUrl, String urlName) {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			File f = new File(DATA_PATH+pathUrl+ "3d_obj.obj");
			if(f.exists()){
				return true;
			}
			FileOutputStream fos = null;
			try {
				URL url = new URL("http://ghdnjs9012.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				if(urlName.charAt(0) >= 'A' && urlName.charAt(0) <= 'G'){
					url = new URL("http://ghdnjs9012.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				}else if(urlName.charAt(0) >= 'H' && urlName.charAt(0) <= 'N'){
					url = new URL("http://ghdnjs1423.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				}else if(urlName.charAt(0) >= 'O' && urlName.charAt(0) <= 'U'){
					url = new URL("http://leesolo369.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				}else{
					url = new URL("http://fantartist.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				}
				InputStream is = url.openStream();
				
				fos = new FileOutputStream(DATA_PATH + pathUrl + "3d_obj.obj");
				double len = 0;
				double tmp = 0;
				byte[] buf = new byte[1024];
				while ((len = is.read(buf)) > 0) {
					tmp += len / 1024 / 1024;
					fos.write(buf, 0, (int) len);
				}
				fos.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} finally {
			}
		}
		return true;
	}
	
	public static boolean loadMtl(Context context, String pathUrl, String urlName) {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			File f = new File(DATA_PATH+"3d/"+ "obj_mtl.mtl");
			if(f.exists()){
				return true;
			}
			FileOutputStream fos = null;
			try {
				URL url = new URL("http://fantartist.megaplug.kr/"+"3d/"+ "obj_mtl.txt");
				InputStream is = url.openStream();
				
				fos = new FileOutputStream(DATA_PATH + "3d/" + "obj_mtl.mtl");
				double len = 0;
				double tmp = 0;
				byte[] buf = new byte[1024];
				while ((len = is.read(buf)) > 0) {
					tmp += len / 1024 / 1024;
					fos.write(buf, 0, (int) len);
				}
				fos.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} finally {
			}
		}
		return true;
	}
	
	public static boolean loadTexture(Context context, String pathUrl, String urlName) {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			File f = new File(DATA_PATH+pathUrl+ "texture.jpg");
			if(f.exists()){
				return true;
			}
			Bitmap imgBitmap = null;
			HttpURLConnection conn = null;
			BufferedInputStream bis = null;
			FileOutputStream fos = null;
			try {
				URL url = new URL("http://ghdnjs9012.megaplug.kr/"+pathUrl+ "texture.jpg");
				if(urlName.charAt(0) >= 'A' && urlName.charAt(0) <= 'G'){
					url = new URL("http://ghdnjs9012.megaplug.kr/"+pathUrl+ "texture.jpg");
				}else if(urlName.charAt(0) >= 'H' && urlName.charAt(0) <= 'N'){
					url = new URL("http://ghdnjs1423.megaplug.kr/"+pathUrl+ "texture.jpg");
				}else if(urlName.charAt(0) >= 'O' && urlName.charAt(0) <= 'U'){
					url = new URL("http://leesolo369.megaplug.kr/"+pathUrl+ "texture.jpg");
				}else{
					url = new URL("http://fantartist.megaplug.kr/"+pathUrl+ "texture.jpg");
				}
				conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				int nSize = conn.getContentLength();
				bis = new BufferedInputStream(conn.getInputStream(), nSize);
				imgBitmap = BitmapFactory.decodeStream(bis);
				
				fos = new FileOutputStream(f);
				imgBitmap.compress(CompressFormat.JPEG, 100, fos);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} finally {
				if (fos != null){
					try {
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		return true;
	}
}
